package com.syqc.sensor.demp

import android.graphics.Color
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import autodispose2.autoDispose
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.github.mikephil.charting.data.LineDataSet
import com.gyf.immersionbar.ktx.immersionBar
import com.syqc.comlib.base.BaseActivity
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.toast
import com.syqc.custom.CircleView
import com.syqc.entity.KeyValue
import com.syqc.entity.ListItem
import com.syqc.entity.TypeInfo
import com.syqc.monitor.R
import com.syqc.monitor.chart.TempDampUtil
import com.syqc.monitor.databinding.ActivityTempDampChartBinding
import com.syqc.utils.DataUtil
import com.syqc.utils.Keys
import com.syqc.utils.Units

/**
 *@author  hfjs
 *@time   2024/11/8 16:03
 *@desc
 */
class TempDampChartActivity :
    BaseActivity<ActivityTempDampChartBinding>(ActivityTempDampChartBinding::inflate) {
    private val mVM by viewModels<TempDampVM>()
    private val mAdapter by lazy { TypeCheckAdapter() }
    private var isShow = false

    private val mTimeAdapter by lazy { TimeAdapter() }
    private val mDataAdapter by lazy { TempDampListAdapter() }
    private val mTypeAdapter by lazy { TempDampTypeAdapter() }
    private val mColorAdapter by lazy { ChartTypeAdapter() }
    private var chartData: ArrayList<LineDataSet>? = null


    override fun initView() {
        immersionBar { titleBar(binding.llToolbar) }
        val date = intent.getStringExtra(Keys.INTENT_DATA) ?: ""
        mVM.unit = intent.getStringExtra(Keys.INTENT_TYPE) ?: "°C"
        val temp =
            if (mVM.unit == "°C") getString(R.string.desc_analog_temp) else getString(R.string.desc_analog_damp)
        val plate = intent.getStringExtra(Keys.INTENT_TITLE) ?: ""
        binding.tvToolbarAction.text = "$plate $temp $date"

        binding.rvTypes.layoutManager = LinearLayoutManager(this)
        binding.rvTypes.adapter = mAdapter
        mAdapter.setList(DataUtil.typeInfos)

        binding.rvTime.layoutManager = GridLayoutManager(this, 8)
        binding.rvTime.adapter = mTimeAdapter

        binding.rvTypeColor.layoutManager = GridLayoutManager(this, 8)
        binding.rvTypeColor.adapter = mColorAdapter

        binding.rvDataList.layoutManager = LinearLayoutManager(this)
        binding.rvDataList.adapter = mDataAdapter
        mDataAdapter.unit = mVM.unit

        TempDampUtil.initTampChart(binding.lineChart, mVM.unit)

        binding.llChart.isVisible = mVM.isChart
        binding.rvDataList.isVisible = !mVM.isChart
        binding.llTypeList.isVisible = !mVM.isChart

        initViewModel()
    }

    override fun setListener() {

        binding.ivToolbarBack.setOnClickListener {
            finish()
        }
        binding.ivChartList.filterFast(700) {
            mVM.isChart = !mVM.isChart
            binding.ivChartList.setImageResource(if (mVM.isChart) R.mipmap.ic_chart_list else R.mipmap.ic_chart_chart)
            binding.llChart.isVisible = mVM.isChart
            binding.rvDataList.isVisible = !mVM.isChart
            binding.llTypeList.isVisible = !mVM.isChart
        }
        binding.llToolbar.filterFast(700) {
            isShow = false
            binding.flSetting.isVisible = isShow
            mVM.refresh()
        }
        binding.ivSetting.filterFast {
            isShow = !isShow
            binding.flSetting.isVisible = isShow
            if (!isShow) mVM.refresh()
        }

        binding.flSetting.filterFast(700) {
            isShow = false
            binding.flSetting.isVisible = isShow
            mVM.refresh()
        }

        binding.rdbChartMile.setOnClickListener {
            mVM.isMile = true
        }

        binding.rdbChartSpeed.setOnClickListener {
            mVM.isMile = false
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val info = mAdapter.data[position]
            val size = mAdapter.data.filter { it.isChecked }.size
            if (info.isChecked && size == 1) {
                toast(getString(R.string.toast_choose_type))
            } else {
                info.isChecked = !info.isChecked
                mAdapter.notifyItemChanged(position)
            }
        }

        mTimeAdapter.setOnItemClickListener { _, _, position ->
            mTimeAdapter.index = position
            mTimeAdapter.notifyDataSetChanged()
            mVM.getOneDayData(mTimeAdapter.data[position])
        }
    }

    private fun initViewModel() {
        mVM.initTypes()
        mVM.initData()
        mVM.toastObserver().autoDispose(scopeProvider).subscribe(::toastObserver)
        mVM.timeLive.observe(this) {
            if (it.size <= 2) {
                binding.rvTime.isVisible = false
                return@observe
            }
            mTimeAdapter.index = 0
            mTimeAdapter.setList(it)
        }

        mVM.listLive.observe(this) {
            mDataAdapter.isMile = mVM.isMile
            binding.tvMileSpeed.text =
                getString(if (mVM.isMile) R.string.desc_com_mile else R.string.desc_com_speed)
            mDataAdapter.setList(it)
        }

        mVM.typeLive.observe(this) {
            if (it.isNotEmpty()) {
                binding.rvTypeList.layoutManager = GridLayoutManager(this, it.size)
                binding.rvTypeList.adapter = mTypeAdapter
                binding.rvTypeList.isEnabled = false
            }

            mTypeAdapter.setList(it)

            mColorAdapter.setList(it)
        }
        mVM.entryLive.observe(this) {
            TempDampUtil.initXAxis2(binding.lineChart, mVM.times)
            chartData = TempDampUtil.setTampData(
                binding.lineChart, mVM.allListItem, mVM.chooseType, it, mVM.unit
            )
            TempDampUtil.change2LineData(binding.lineChart, chartData!!, mVM.isMile)

            binding.cMileSpeed.circleColor =
                Color.parseColor(
                    if (mVM.isMile) TempDampUtil.lineColors[0] else TempDampUtil.lineColors[1]
                )
            binding.tvMileSpeedColor.setText(
                if (mVM.isMile) R.string.desc_com_mile else R.string.desc_com_speed
            )
        }
    }


}

class TypeCheckAdapter() :
    BaseQuickAdapter<TypeInfo, BaseViewHolder>(R.layout.item_type_check) {
    override fun convert(
        holder: BaseViewHolder,
        item: TypeInfo
    ) {
        item.run {
            val tvType = holder.getView<TextView>(R.id.tvType)
            tvType.isSelected = isChecked
            tvType.text = typeName
        }

    }
}

class ChartTypeAdapter : BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_type_chart) {
    override fun convert(
        holder: BaseViewHolder,
        item: String
    ) {
        holder.setText(R.id.tvTitle, item)
        val cColor = holder.getView<CircleView>(R.id.cColor)
        val color = TempDampUtil.lineColors[holder.layoutPosition + 2]
        cColor.circleColor = Color.parseColor(color)
    }
}

class TempDampListAdapter : BaseQuickAdapter<ListItem, BaseViewHolder>(R.layout.item_temp_damp) {
    var isMile = true
    var unit = ""
    override fun convert(holder: BaseViewHolder, item: ListItem) {
        item.run {
            holder.setText(R.id.tvTime, time)
                .setText(
                    R.id.tvMileSpeed,
                    if (isMile) "$mile ${Units.km}" else "$speed ${Units.speed}"
                )
            val rvTempDamp = holder.getView<RecyclerView>(R.id.rvList)
            if (list.isNotEmpty()) {
                rvTempDamp.layoutManager = GridLayoutManager(context, list.size)
                rvTempDamp.isEnabled = false
                rvTempDamp.adapter = TempDampAdapter(unit).apply { setList(list) }
            }
        }
    }
}

class TempDampTypeAdapter() :
    BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_temp_damp_time) {
    override fun convert(
        holder: BaseViewHolder,
        item: String
    ) {
        holder.setText(R.id.item_choose_time, item)
    }

}

class TempDampAdapter(private val unit: String = "") :
    BaseQuickAdapter<KeyValue, BaseViewHolder>(R.layout.item_temp_damp_time) {
    override fun convert(
        holder: BaseViewHolder,
        item: KeyValue
    ) {
        holder.setText(R.id.item_choose_time, "${item.value}$unit")
    }

}

class TimeAdapter : BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_temp_time) {
    var index = 0
    override fun convert(holder: BaseViewHolder, item: String) {
        val chooseTime = holder.getView<TextView>(R.id.item_choose_time)
        chooseTime.text = item
        chooseTime.isSelected = index == holder.layoutPosition
    }
}